package com.redstar.expenses;

import java.util.Calendar;
import java.util.Currency;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockMapActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class ModifyExpense extends SherlockMapActivity implements LocationListener  {

	private Expense exp;
	private DatabaseHelper db;
	//The users currency
	private Currency money;
	//views
	private TextView DateAndTimeTV;
	private TextView ShopInputTV;
	private TextView ItemInputTV;
	private TextView CurrencyTV;
	private TextView CostInputTV;
	//map and location items
	private MapController myMapController;
	private MapView mapView;
	private GeoPoint point;
	private List<Overlay> mapOverlays;
	private Drawable drawable;
	private ExpenseItemizedOverlay itemizedoverlay;
	private OverlayItem overlayitem;
	//action bar items
	private final int SAVE_EXPENSE = 1;
	//dialogs
	static final int TIME_DATE_DIALOG_ID = 2;
	static final int SHOP_DIALOG_ID = 3;
	static final int ITEM_DIALOG_ID = 4;
	static final int COST_DIALOG_ID = 5;
	static final int CURRENCY_DIALOG_ID = 6;
	//shared preferences
	// public static final String PREFS_NAME = "MyPrefsFile";
	
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setContentView(R.layout.modify);
        //preferences
        //SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        
        //get passed in expense
        Intent i = getIntent();
        exp = (Expense)i.getSerializableExtra("Expense");
        
      
        money = Currency.getInstance(exp.getCurrencyCode());
        
        //populate views
        DateAndTimeTV = (TextView) findViewById(R.id.DateAndTimeTV);
        DateAndTimeTV.setText("Date and Time: \n" + exp.getTimeDateString());
        DateAndTimeTV.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(TIME_DATE_DIALOG_ID);
			}
        	
        });
        
        ShopInputTV = (TextView) findViewById(R.id.ShopInputTV);
        ShopInputTV.setText(exp.getShop());
        ShopInputTV.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(SHOP_DIALOG_ID);
			}
        	
        });
        
        ItemInputTV = (TextView) findViewById(R.id.ItemInputTV);
        ItemInputTV.setText(exp.getItem());
        ItemInputTV.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(ITEM_DIALOG_ID);
			}
        	
        });        
        
        CurrencyTV = (TextView) findViewById(R.id.CurrencyTV);
        CurrencyTV.setText(money.getSymbol());
        CurrencyTV.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(CURRENCY_DIALOG_ID);
			}
        	
        });        
        
        CostInputTV = (TextView) findViewById(R.id.CostInputTV);
        if(exp.getCost()>-1){
        	CostInputTV.setText(String.format("%." + money.getDefaultFractionDigits() + "f", exp.getCost()));
        }
    
        
        CostInputTV.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(COST_DIALOG_ID);
			}
        	
        });  
        
        db = new DatabaseHelper(this);
        
        
        //maps
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        itemizedoverlay = new ExpenseItemizedOverlay(drawable, this);
        mapOverlays = mapView.getOverlays();
      
        //set controls
        myMapController = mapView.getController();
        myMapController.setZoom(15);        
       
        //if the expense has no location attached
        if(exp.getLat()==-1){
            //get location
            LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);       	
        }
        else{
        	//show the saved location
            //show the location and marker
            point = new GeoPoint(exp.getLat(), exp.getLong());
            overlayitem = new OverlayItem(point, "Hola, Mundo!", "Lat :" + exp.getLat() + "\nLong :" + exp.getLong());
            itemizedoverlay.addOverlay(overlayitem);
            mapOverlays.add(itemizedoverlay);
            myMapController.animateTo(point);
        }
        
    }
    
	protected AlertDialog onCreateDialog(int id) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);//<=====THIS
		final AlertDialog dialog;
		
	    switch(id) {
	    	case TIME_DATE_DIALOG_ID:
	    		builder.setTitle("Set the Date/Time");
	    		LayoutInflater layoutInflater 
	    		  = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    		final View view=layoutInflater.inflate(R.layout.date_time_picker,null);   
	    		builder.setView(view);
	    		builder.setCancelable(true);
	    		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	                TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker1);
	    	                DatePicker dp = (DatePicker) view.findViewById(R.id.datePicker1);
	    	                
	    	                Calendar c = Calendar.getInstance();
	    	                c.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(), tp.getCurrentHour(), tp.getCurrentMinute());
	    	                exp.setTimeDate(c);
	    	                DateAndTimeTV.setText("Date and Time: \n" + exp.getTimeDateString());
	    	           }
	    	       });
	    		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	                dialog.cancel();
	    	           }
	    	       });
	    		dialog = builder.create();
	    		break;

	    	case SHOP_DIALOG_ID:
	    		builder.setTitle("What Shop?");
	    		// Set an EditText view to get user input   
	    		final EditText ShopInput = new EditText(this); 
	    		builder.setView(ShopInput);
	    		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int id) {
	    				exp.setShop(ShopInput.getText().toString());
	    				ShopInputTV.setText(exp.getShop());
	    	           }
	    	       });
	    		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	                dialog.cancel();
	    	           }
	    	       });
	    		dialog = builder.create();
	    		break;
	    		
	    	case ITEM_DIALOG_ID:
	    		builder.setTitle("What Did You Buy?");
	    		// Set an EditText view to get user input   
	    		final EditText ItemInput = new EditText(this); 
	    		builder.setView(ItemInput);
	    		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int id) {
	    				exp.setItem(ItemInput.getText().toString());
	    				ItemInputTV.setText(exp.getItem());
	    	           }
	    	       });
	    		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	                dialog.cancel();
	    	           }
	    	       });
	    		dialog = builder.create();
	    		break;	    
	    		
	    		
	    	case COST_DIALOG_ID:
	    		builder.setTitle("How Much?");
	    		// Set an EditText view to get user input   
	    		final EditText CostInput = new EditText(this); 
	    		CostInput.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
	    		builder.setView(CostInput);
	    		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    			public void onClick(DialogInterface dialog, int id) {
	    				try{
		    				exp.setCost(Double.parseDouble(CostInput.getText().toString()));
		    				CostInputTV.setText(String.format("%." + money.getDefaultFractionDigits() + "f", exp.getCost()));	    					
	    				}catch ( NumberFormatException ex ){
	    					Toast.makeText(getApplicationContext(), "Please enter a number", Toast.LENGTH_SHORT).show();
	    				}

	    	       }
	    	    });
	    		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	                dialog.cancel();
	    	           }
	    	       });
	    		dialog = builder.create();
	    		break;	  	    	
	    	
	    	case CURRENCY_DIALOG_ID:
	    		// get list of available currencys 
	    		final String[] stringArray = getResources().getStringArray(R.array.code);
	    		
	    		builder.setTitle("Pick Your Currency");
	    		builder.setItems(stringArray, new DialogInterface.OnClickListener() {
	    		    public void onClick(DialogInterface dialog, int item) {
	    		         // Do something with the selection
	    		    	int spaceIndex = stringArray[item].indexOf(" ");
	    		    	exp.setCurrencyCode(stringArray[item].substring(0, spaceIndex));
	    		    	money = Currency.getInstance(exp.getCurrencyCode());
	    		    	CurrencyTV.setText(money.getSymbol());
	    		    	if(exp.getCost()>-1){
	    			        	CostInputTV.setText(String.format("%." + money.getDefaultFractionDigits() + "f", exp.getCost()));
	    			    }
	    		    	//Save preference
	    		    	SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
	    		        SharedPreferences.Editor prefsEditor = myPrefs.edit();
	    		        prefsEditor.putString("CURRENCY", stringArray[item].substring(0, spaceIndex));
	    		        prefsEditor.commit();
	    		    	
	    		    	Toast.makeText(getApplicationContext(), "prefrence set to:" + myPrefs.getString("CURRENCY", "") , Toast.LENGTH_SHORT).show();
	    		    }
	    		});
	    		
	    		dialog = builder.create();    		
	    		break;	
	    		
	    		
	    	default:
	    	dialog = null;
	    }
	    return dialog;
	}

    
    @Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
        
		Intent intent = new Intent(this, ExpenseList.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; go home
            startActivity(intent);
            return true;
        case SAVE_EXPENSE:
            // app icon in action bar clicked; save and go home
        	saveExpense();
            startActivity(intent);
            return true;         
            
        default:
            return super.onOptionsItemSelected(item);
	    }
	}
	
	//Update the passed in expense with info from views and save to database
    private void saveExpense() {
		// if its new add
    	if(exp.getID()==-1){
        	db.addExpense(exp);
        	Toast.makeText(getApplicationContext(), "Expense Added", Toast.LENGTH_SHORT).show();
    	}
    	// otherwise update
    	else{
    		db.updateContact(exp);
    		Toast.makeText(getApplicationContext(), "Expense Updated", Toast.LENGTH_SHORT).show();
    	}
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0,SAVE_EXPENSE,1,"Save")
        .setIcon(android.R.drawable.ic_menu_save)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		
        return true;
   }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			point = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
			//update expense
			exp.setLat((int) (lat * 1000000));
			exp.setLong((int) (lng * 1000000));
			//clear overlays
			mapView.getOverlays().clear();
			mapView.invalidate();
			itemizedoverlay.clear();
			mapOverlays.clear();
			
			//add new point
			overlayitem = new OverlayItem(point, "Hola, Mundo!", "Lat :" + exp.getLat() + "\nLong :" + exp.getLong());
	        itemizedoverlay.addOverlay(overlayitem);
	        mapOverlays.add(itemizedoverlay);	
			myMapController.animateTo(point);
			}		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
